﻿using System;
using System.Net;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Data.Services.Client;
using System.IO.IsolatedStorage;
using System.Xml.Linq;
using System.Threading;
using Ivvy_Silverlight.i7SR;
using Infragistics.Controls.Schedules;
using Infragistics;
using Sqo;

namespace Ivvy_Silverlight.Ivvy
{
    public class DataManipulations
    {
        public static string IvyySiaqodbName = "IvyySiaqodbName";
        const string DefaultODataServiceURL = "http://localhost:11080/i7s.svc/";
        public string ODataServiceURL = string.Empty;
        public i7e svc = null;
        public ClientData Data;
        public Siaqodb siaqodb = null;
        public DateRange? VisibleDatesinMonthView = null;
        public event EventHandler<EventArgs> LoadCollectionsCompleted = null;
        public event EventHandler<EventArgs> LoadCollectionsProgressCallbak = null;
        public event EventHandler<EventArgs> LoadSaveDataCompletedCallbak = null;
        public event EventHandler<EventArgs> SaveOneCalendarIremCallbak = null;
        public event EventHandler<EventArgs> GetAppointment_DetailFromODataServerCallbak = null;
        
        public int CountOfRecordsOfAllTables = 0;
        public const int ManualODataPageSize = 2000;
        public const int ManualODataPageSize_CalendarItem_Field = 10000;
        public const string ODataSkipParam = "$skip";
        public const string ODataTopParam = "$top";
        public const string DayMonthViewOwningResourceId = "Own1";
        public const string DayMonthViewResourceName = "Amanda";
        public const string DayMonthViewResourceCalendarId = "cal1";
                
        public DataManipulations()//constructor
        {
            ODataServiceURL = DefaultODataServiceURL;
            Initilize();            
        }

        public DataManipulations(string NewODataServiceURL)//constructor
        {
            ODataServiceURL = NewODataServiceURL;
            Initilize();
        }//public DataManipulations(string NewODataServiceURL)//constructor

        protected void Initilize()
        {
            InitSvc();
            siaqodb = new Siaqodb(DataManipulations.IvyySiaqodbName);
            Data = new ClientData();
        }//protected void Initilize()

        protected void InitSvc()
        {
            svc = new i7e(new Uri(ODataServiceURL, UriKind.Absolute));
        }

        public void LoadCollectionsFromOData()
        {
            Data.ClearAll();
            CountOfRecordsOfAllTables = 0;
            Thread Download_and_ParseThread = new Thread(GetCountOfRecordsOfAllTablesFromOData);
            Download_and_ParseThread.Start();            
        }//public void LoadCollectionsFromOData()

        private void GetCountOfRecordsOfAllTablesFromOData()
        {
            WebClient GetCountOfRecordsOfAllTablesFromOData_webC = new WebClient();
            GetCountOfRecordsOfAllTablesFromOData_webC.DownloadStringCompleted += new DownloadStringCompletedEventHandler(GetCountOfRecordsOfAllTablesFromOData_DownloadStringCompleted);
            GetCountOfRecordsOfAllTablesFromOData_webC.DownloadStringAsync(new Uri(ODataServiceURL + "GetCountOfRecordsOfAllTables"));
        }

        private void GetCountOfRecordsOfAllTablesFromOData_DownloadStringCompleted(object Sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                XDocument xDocument = XDocument.Parse(e.Result as string);                
                CountOfRecordsOfAllTables = Convert.ToInt32(xDocument.Root.Value);
                Loadvw_Appointment_Summary();
                
            }//if (e.Error == null)
        }//void CalendarItems_DownloadStringCompleted(object Sender, DownloadStringCompletedEventArgs e)

        public void Loadvw_Appointment_Summary()
        {
            var query = (VisibleDatesinMonthView.HasValue ?
                svc.vw_Appointment_Summary.Where(a => a.Start_Date >= VisibleDatesinMonthView.Value.Start && a.Start_Date.Value <= VisibleDatesinMonthView.Value.End) :
                svc.vw_Appointment_Summary) as DataServiceQuery;
            query.BeginExecute(vw_Appointment_SummarysC_LoadCompleted, query);
        }//private void Loadvw_Appointment_Summary()

        private void vw_Appointment_SummarysC_LoadCompleted(IAsyncResult result)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                var queryResult = result.AsyncState as DataServiceQuery<vw_Appointment_Summary>;
                if (queryResult != null)
                {
                    var vw_Appointment_SummarysFromOdata = queryResult.EndExecute(result);
                    bool IsFirstRun = Data.vw_Appointment_SummaryC.Count == 0;
                    foreach (var Currentvw_Appointment_Summary in vw_Appointment_SummarysFromOdata)
                        if (Data.vw_Appointment_SummaryC.IndexOf(i_vw_Appointment_Summary.Convert( Currentvw_Appointment_Summary)) == -1)
                            Data.vw_Appointment_SummaryC.Add(i_vw_Appointment_Summary.Convert (Currentvw_Appointment_Summary));                    
                    if (LoadCollectionsCompleted != null)
                        LoadCollectionsCompleted(this, new EventArgs());

                    if (IsFirstRun)
                        LoadFirstPart_via_CustomODataFunctions();
                }
            });
        }//private void vw_Appointment_SummarysC_LoadCompleted(IAsyncResult result)


        private void LoadFirstPart_via_CustomODataFunctions()
        {
            ShowTotalLoadProgress();
            WebClient CalendarItems_webC = new WebClient();
            CalendarItems_webC.DownloadStringCompleted += new DownloadStringCompletedEventHandler(CalendarItems_DownloadStringCompleted);
            CalendarItems_webC.DownloadStringAsync(new Uri(ODataServiceURL + "i_GetCalendarItems_in_Binary_via_CustomFunction"));
        }//private void LoadFirstPart_via_CustomODataFunctions()
         
        void CalendarItems_DownloadStringCompleted(object Sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                Thread ParseThread = new Thread(CalendarItems_ParseThread);
                ParseThread.Start(e.Result);
                LoadSecondPart_via_CustomODataFunctions();
            }//if (e.Error == null)
        }//void CalendarItems_DownloadStringCompleted(object Sender, DownloadStringCompletedEventArgs e)

        private void CalendarItems_ParseThread(object DoParseThreadParam)
        {
            Data.CalendarItemsC = (ObservableCollection<i_CalendarItem>)SaveLoad.LoadFromBinary(FromXMLCustomOData_toBinary(DoParseThreadParam as string));
            ShowTotalLoadProgress();
        }//private void CalendarItems_ParseThread(object DoParseThreadParam)


        private void LoadSecondPart_via_CustomODataFunctions()
        {
            WebClient CalendarItem_Fields_webC = new WebClient();
            CalendarItem_Fields_webC.DownloadStringCompleted += new DownloadStringCompletedEventHandler(CalendarItem_Fields_DownloadStringCompleted);
            CalendarItem_Fields_webC.DownloadStringAsync(new Uri(ODataServiceURL + "i_GetCalendarItemFields_in_Binary_via_CustomFunction"));
        }//private void LoadSecondPart_via_CustomODataFunctions()

        void CalendarItem_Fields_DownloadStringCompleted(object Sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                Thread ParseThread = new Thread(CalendarItem_Fields_ParseThread);
                ParseThread.Start(e.Result);
                LoadThirdPart_via_CustomODataFunctions();
            }//if (e.Error == null)
        }//void CalendarItem_Fields_DownloadStringCompleted(object Sender, DownloadStringCompletedEventArgs e)

        private void CalendarItem_Fields_ParseThread(object DoParseThreadParam)
        {
            Data.CalendarItem_FieldC = (ObservableCollection<i_CalendarItem_Field>)SaveLoad.LoadFromBinary(FromXMLCustomOData_toBinary(DoParseThreadParam as string));
            ShowTotalLoadProgress();
        }//private void CalendarItem_Fields_ParseThread(object DoParseThreadParam)

        private void LoadThirdPart_via_CustomODataFunctions()
        {
            WebClient vw_CalendarItem_Notes_webC = new WebClient();
            vw_CalendarItem_Notes_webC.DownloadStringCompleted += new DownloadStringCompletedEventHandler(vw_CalendarItem_Notes_DownloadStringCompleted);
            vw_CalendarItem_Notes_webC.DownloadStringAsync(new Uri(ODataServiceURL + "i_Getvw_CalendarItem_Notes_in_Binary_via_CustomFunction"));
        }//private void LoadThirdPart_via_CustomODataFunctions()

        void vw_CalendarItem_Notes_DownloadStringCompleted(object Sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                Thread ParseThread = new Thread(vw_CalendarItem_Notes_ParseThread);
                ParseThread.Start(e.Result);
                LoadFourthPart_via_CustomODataFunctions();
            }//if (e.Error == null)
        }//void vw_CalendarItem_Notes_DownloadStringCompleted(object Sender, DownloadStringCompletedEventArgs e)

        private void vw_CalendarItem_Notes_ParseThread(object DoParseThreadParam)
        {   
            Data.vw_CalendarItem_NoteC = (ObservableCollection<i_vw_CalendarItem_Note>)SaveLoad.LoadFromBinary(FromXMLCustomOData_toBinary(DoParseThreadParam as string));
            ShowTotalLoadProgress();
        }//private void vw_CalendarItem_Notes_ParseThread(object DoParseThreadParam)

        public static byte[] FromXMLCustomOData_toBinary(string XMLFromServer)
        {
            XDocument xDocument = XDocument.Parse(XMLFromServer);            
            return Convert.FromBase64String(xDocument.Root.Value);
            
        }

        private void LoadFourthPart_via_CustomODataFunctions()
        {
            WebClient MUTLI_TABLESs_webC = new WebClient();
            MUTLI_TABLESs_webC.DownloadStringCompleted += new DownloadStringCompletedEventHandler(MUTLI_TABLES_DownloadStringCompleted);
            MUTLI_TABLESs_webC.DownloadStringAsync(new Uri(ODataServiceURL + "i_GetMUTLI_TABLES__in_Binary_via_CustomFunction"));
        }


        void MUTLI_TABLES_DownloadStringCompleted(object Sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                Thread ParseThread = new Thread(MUTLI_TABLES_ParseThread);
                ParseThread.Start(e.Result);
            }//if (e.Error == null)
        }//void vw_CalendarItem_Notes_DownloadStringCompleted(object Sender, DownloadStringCompletedEventArgs e)

        private void MUTLI_TABLES_ParseThread(object DoParseThreadParam)
        {            
            ObservableCollection<object> MUTLI_TABLES =
                 (ObservableCollection<object>)SaveLoad.LoadFromBinary(DataManipulations.FromXMLCustomOData_toBinary(DoParseThreadParam as string));
            ShowTotalLoadProgress();
            foreach (var CurMUTLI_TABLES in MUTLI_TABLES)
                if (CurMUTLI_TABLES is ObservableCollection<i_Entry>)
                    Data.EntryC = CurMUTLI_TABLES as ObservableCollection<i_Entry>;
                else if (CurMUTLI_TABLES is ObservableCollection<i_Entry_Field>)
                    Data.Entry_FieldC = CurMUTLI_TABLES as ObservableCollection<i_Entry_Field>;
                else if (CurMUTLI_TABLES is ObservableCollection<i_Field>)
                    Data.FieldC = CurMUTLI_TABLES as ObservableCollection<i_Field>;
                else if (CurMUTLI_TABLES is ObservableCollection<i_Field_Details>)
                    Data.Field_DetailsC = CurMUTLI_TABLES as ObservableCollection<i_Field_Details>;
                else if (CurMUTLI_TABLES is ObservableCollection<i_Field_Type>)
                    Data.Field_TypeC = CurMUTLI_TABLES as ObservableCollection<i_Field_Type>;
                else if (CurMUTLI_TABLES is ObservableCollection<i_Verb>)
                    Data.VerbC = CurMUTLI_TABLES as ObservableCollection<i_Verb>;
                else if (CurMUTLI_TABLES is ObservableCollection<i_Status>)
                    Data.StatusC = CurMUTLI_TABLES as ObservableCollection<i_Status>;
                else if (CurMUTLI_TABLES is ObservableCollection<i_CalendarItem_Related>)
                    Data.CalendarItem_RelatedC = CurMUTLI_TABLES as ObservableCollection<i_CalendarItem_Related>;
                else if (CurMUTLI_TABLES is ObservableCollection<i_CalendarItemRecurrence>)
                    Data.CalendarItemRecurrenceC = CurMUTLI_TABLES as ObservableCollection<i_CalendarItemRecurrence>;
                else if (CurMUTLI_TABLES is ObservableCollection<i_Calendar>)
                    Data.CalendarsC = CurMUTLI_TABLES as ObservableCollection<i_Calendar>;
            ShowTotalLoadProgress();
        }

        public void ShowTotalLoadProgress()
        {
            if (LoadCollectionsProgressCallbak != null)
                LoadCollectionsProgressCallbak(((int) ( (((double)Data.GetTotalCount()) / ((double)CountOfRecordsOfAllTables)) * 100 )).ToString() + "%", new EventArgs());
        }
               

        public void SaveToIStorageinXML()
        {
            Thread Thread_SaveToIStorageinXML = new Thread(DoSaveToIStorageinXML_Thread);
            Thread_SaveToIStorageinXML.Start();
        }//public void SaveToIStorageinXML()        {           

        public void DoSaveToIStorageinXML_Thread()
        {
            string DataInXML = SaveLoad.SaveToXMLData(Data);
            SaveLoad.SaveStringDataToLocalStorage(DataInXML, SaveLoad.IvvySilverlightFileNameinIsolatedStorage);
            ProcessLoadSaveDataCompletedCallbak();
        }

        public void ProcessLoadSaveDataCompletedCallbak()
        {
            if (LoadSaveDataCompletedCallbak != null)
                LoadSaveDataCompletedCallbak(this, new EventArgs());
        }

        public bool LoadFromIStorageinXML()
        {
            if (IsolatedStorageFile.GetUserStoreForApplication().FileExists(SaveLoad.IvvySilverlightFileNameinIsolatedStorage))
            {
                Thread Thread_LoadFromIStorageinXML = new Thread(DoLoadFromIStorageinXML_Thread);
                Thread_LoadFromIStorageinXML.Start();
                return true;
            }
            else
                return false;
        }//public bool LoadFromIStorageinXML()


        public void DoLoadFromIStorageinXML_Thread()
        {   
            Data.ClearAll();
            string DataInXML = SaveLoad.LoadStringDataFromLocalStorage(SaveLoad.IvvySilverlightFileNameinIsolatedStorage);
            Data = (ClientData)SaveLoad.LoadFromXML(DataInXML, Data.GetType());             
            ProcessLoadSaveDataCompletedCallbak();
        }

        public void SaveToIStorageviaSiaqodb()
        {
            Thread Thread_SaveToIStorageviaSiaqodb = new Thread(DoSaveToIStorageviaSiaqodb_Thread);
            Thread_SaveToIStorageviaSiaqodb.Start();
        }//public void SaveToIStorageinXML()        {           

        public void DoSaveToIStorageviaSiaqodb_Thread()
        {
            siaqodb.DropType<i_CalendarItem>();
            foreach (var CurCI in Data.CalendarItemsC)
                siaqodb.StoreObject(CurCI);
            siaqodb.DropType<i_CalendarItem_Field>();
            foreach (var CurCI in Data.CalendarItem_FieldC)
                siaqodb.StoreObject(CurCI);
            siaqodb.DropType<i_vw_CalendarItem_Note>();
            foreach (var CurCI in Data.vw_CalendarItem_NoteC)
                siaqodb.StoreObject(CurCI);
            siaqodb.DropType<i_Entry>();
            foreach (var CurEntry in Data.EntryC)
                siaqodb.StoreObject(CurEntry);
            siaqodb.DropType<i_Entry_Field>();
            foreach (var CurEntry_Field in Data.Entry_FieldC)
                siaqodb.StoreObject(CurEntry_Field);
            siaqodb.DropType<i_Field>();
            foreach (var CurField in Data.FieldC)
                siaqodb.StoreObject(CurField);
            siaqodb.DropType<i_Field_Details>();
            foreach (var CurField_Details in Data.Field_DetailsC)
                siaqodb.StoreObject(CurField_Details);
            siaqodb.DropType<i_Field_Type>();
            foreach (var CurField_Type in Data.Field_TypeC)
                siaqodb.StoreObject(CurField_Type);
            siaqodb.DropType<i_Verb>();
            foreach (var CurVerb in Data.VerbC)
                siaqodb.StoreObject(CurVerb);
            siaqodb.DropType<i_Status>();
            foreach (var CurStatus in Data.StatusC)
                siaqodb.StoreObject(CurStatus);
            siaqodb.DropType<i_CalendarItem_Related>();
            foreach (var CurCalendarItem_Related in Data.CalendarItem_RelatedC)
                siaqodb.StoreObject(CurCalendarItem_Related);
            siaqodb.DropType<i_CalendarItemRecurrence>();
            foreach (var CurCalendarItemRecurrence in Data.CalendarItemRecurrenceC)
                siaqodb.StoreObject(CurCalendarItemRecurrence);
            siaqodb.DropType<i_Calendar>();
            foreach (var CurCalendar in Data.CalendarsC)
                siaqodb.StoreObject(CurCalendar);
            siaqodb.DropType<i_vw_Appointment_Summary>();
            foreach (var Curvw_Appointment_Summary in Data.vw_Appointment_SummaryC)
                siaqodb.StoreObject(Curvw_Appointment_Summary);
            siaqodb.Flush();
            ProcessLoadSaveDataCompletedCallbak();
        }//public void DoSaveToIStorageviaSiaqodb_Thread()
        
        public bool LoadFromIStorageviaSiaqodb()
        {
            Thread Thread_LoadFromIStorageviaSiaqodb = new Thread(DoLoadFromIStorageviaSiaqodb_Thread);
           Thread_LoadFromIStorageviaSiaqodb.Start();
            return true;
            
        }//public bool LoadFromIStorageviaSiaqodb()


        public void DoLoadFromIStorageviaSiaqodb_Thread()
        {
            Data.ClearAll();
            IObjectList<i_CalendarItem> NewCalItem = siaqodb.LoadAll<i_CalendarItem>();
            foreach (var CurItem in NewCalItem)
                Data.CalendarItemsC.Add(CurItem);
            IObjectList<i_CalendarItem_Field> NewCal_FieldItem = siaqodb.LoadAll<i_CalendarItem_Field>();
            foreach (var CurItem in NewCal_FieldItem)
                Data.CalendarItem_FieldC.Add(CurItem);            
            IObjectList<i_vw_CalendarItem_Note> Newvw_CalendarItem_NoteItem = siaqodb.LoadAll<i_vw_CalendarItem_Note>();            
            foreach (var CurItem in Newvw_CalendarItem_NoteItem)
                Data.vw_CalendarItem_NoteC.Add(CurItem);
            IObjectList<i_Entry> NewEntryItem = siaqodb.LoadAll<i_Entry>();            
            foreach (var CurItem in NewEntryItem)
                Data.EntryC.Add(CurItem);
            IObjectList<i_Entry_Field> NewEntry_FieldItem = siaqodb.LoadAll<i_Entry_Field>();            
            foreach (var CurItem in NewEntry_FieldItem)
                Data.Entry_FieldC.Add(CurItem);
            IObjectList<i_Field> NewFieldItem = siaqodb.LoadAll<i_Field>();            
            foreach (var CurItem in NewFieldItem)
                Data.FieldC.Add(CurItem);
            IObjectList<i_Field_Details> NewField_Details = siaqodb.LoadAll<i_Field_Details>();            
            foreach (var CurItem in NewField_Details)
                Data.Field_DetailsC.Add(CurItem);
            IObjectList<i_Field_Type> NewField_Type = siaqodb.LoadAll<i_Field_Type>();            
            foreach (var CurItem in NewField_Type)
                Data.Field_TypeC.Add(CurItem);
            IObjectList<i_Verb> NewVerb = siaqodb.LoadAll<i_Verb>();            
            foreach (var CurItem in NewVerb)
                Data.VerbC.Add(CurItem);
            IObjectList<i_Status> NewStatus = siaqodb.LoadAll<i_Status>();            
            foreach (var CurItem in NewStatus)
                Data.StatusC.Add(CurItem);
            IObjectList<i_CalendarItem_Related> NewCalendarItem_Related = siaqodb.LoadAll<i_CalendarItem_Related>();            
            foreach (var CurItem in NewCalendarItem_Related)
                Data.CalendarItem_RelatedC.Add(CurItem);
            IObjectList<i_CalendarItemRecurrence> NewCalendarItemRecurrence = siaqodb.LoadAll<i_CalendarItemRecurrence>();            
            foreach (var CurItem in NewCalendarItemRecurrence)
                Data.CalendarItemRecurrenceC.Add(CurItem);
            IObjectList<i_Calendar> NewCalendar = siaqodb.LoadAll<i_Calendar>();            
            foreach (var CurItem in NewCalendar)
                Data.CalendarsC.Add(CurItem);
            IObjectList<i_vw_Appointment_Summary> Newvw_Appointment_Summary = siaqodb.LoadAll<i_vw_Appointment_Summary>();
            foreach (var CurItem in Newvw_Appointment_Summary)
                Data.vw_Appointment_SummaryC.Add(CurItem);
                       

            ProcessLoadSaveDataCompletedCallbak();
        }//public void DoLoadFromIStorageviaSiaqodb_Thread()


        public void SaveToIStorageinBinary()
        {
            Thread Thread_SaveToIStorageinBinary = new Thread(DoSaveToIStorageinBinary_Thread);
            Thread_SaveToIStorageinBinary.Start();
        }//public void SaveToIStorageinBinary()        
            
        public void DoSaveToIStorageinBinary_Thread()
        {
            byte[] DataInBinary = SaveLoad.SaveToBinary(Data);
            SaveLoad.SaveBinaryDataToLocalStorage(DataInBinary, SaveLoad.IvvySilverlightFileNameinIsolatedStorageBinary);
            ProcessLoadSaveDataCompletedCallbak();
        }
        
        public bool LoadFromIStorageinBinary()
        {
            if (IsolatedStorageFile.GetUserStoreForApplication().FileExists(SaveLoad.IvvySilverlightFileNameinIsolatedStorageBinary))
            {
                Thread Thread_LoadFromIStorageinBinary = new Thread(DoLoadFromIStorageinBinary_Thread);
                Thread_LoadFromIStorageinBinary.Start();
                return true;
            }
            else
                return false;
        }//public bool LoadFromIStorageinBinary()

        public void DoLoadFromIStorageinBinary_Thread()
        {
            Data.ClearAll();
            byte[] DataInBinary = SaveLoad.LoadBinaryDataFromLocalStorage(SaveLoad.IvvySilverlightFileNameinIsolatedStorageBinary);
            Data = (ClientData)SaveLoad.LoadFromBinary(DataInBinary);
            ProcessLoadSaveDataCompletedCallbak();
        }


        public DateRange? BindDataToScheduleDataManager(XamScheduleDataManager xamScheduleDataManager, bool NeedClear = true)
        {
            if (NeedClear)
            {
                ((ObservableCollection<Appointment>)((ListScheduleDataConnector)xamScheduleDataManager.DataConnector).AppointmentItemsSource).Clear();
                ((ListScheduleDataConnector)xamScheduleDataManager.DataConnector).AppointmentItemsSource = new ObservableCollection<Appointment>();
                ExtendedAppoIntMent.CurId = 0;
            }
            
            bool FirstCalendarI = true;
            DateRange? SelectedTimeRange = null;
            foreach (var CurAppointment_Summary in Data.vw_Appointment_SummaryC)
            {
                bool AlreadyExist = false;
                foreach(var CurrentAppointment in ((ObservableCollection<Appointment>)((ListScheduleDataConnector)xamScheduleDataManager.DataConnector).AppointmentItemsSource))
                    if(CurrentAppointment is ExtendedAppoIntMent)
                        if ((CurrentAppointment as ExtendedAppoIntMent).Appointment_Summary.CalendarItem_ID == CurAppointment_Summary.CalendarItem_ID)
                    {
                        AlreadyExist = true;
                        break;
                    }

                if (!AlreadyExist)
                {
                    if (FirstCalendarI)
                    {
                        DateTime StartDT = CurAppointment_Summary.Start_Date;
                        DateTime StartDR = new DateTime(StartDT.Year, StartDT.Month, StartDT.Day);
                        SelectedTimeRange = new Infragistics.DateRange(StartDR, StartDR.AddDays(1));
                        FirstCalendarI = false;
                    }
                    ExtendedAppoIntMent newapp = new ExtendedAppoIntMent()
                    {
                        Id = ExtendedAppoIntMent.GetNextAppointmentID(),
                        OwningResourceId = DayMonthViewOwningResourceId,
                        OwningCalendarId = DayMonthViewResourceCalendarId,
                        Subject = CurAppointment_Summary.Salutation + " " + 
                                                (CurAppointment_Summary.FirstName != null ? CurAppointment_Summary.FirstName.TrimEnd() : string.Empty) + 
                                             " " + CurAppointment_Summary.MiddleName.TrimEnd() + " " + CurAppointment_Summary.LastName.TrimEnd(),
                        Location = CurAppointment_Summary.Verb,
                        Description = CurAppointment_Summary.Entry_Name,
                        Start = CurAppointment_Summary.Start_Date,
                        End = CurAppointment_Summary.End_Date,
                        Appointment_Summary = CurAppointment_Summary
                    };

                    newapp.SetFillColorExFrom_StatusID(CurAppointment_Summary.Status_ID);
                    ((ObservableCollection<Appointment>)((ListScheduleDataConnector)xamScheduleDataManager.DataConnector).AppointmentItemsSource).Add(newapp);
                }//if (!AlreadyExist)
            }//foreach (var CurCalendarI in CalendarItemBinding)
            return SelectedTimeRange;
        }//public void BindDataToMonthViewControl(XamMonthView MonthView)

        public i_CalendarItem FindCalendarItemViaID(int CalendarItemID)
        {
            foreach (var CurrentCalendarItem in Data.CalendarItemsC)
                if (CurrentCalendarItem.CalendarItem_ID == CalendarItemID)
                    return CurrentCalendarItem;
            return null;
        }//private CalendarItem FindCalendarItemViaID(int CalendarItemID)


        public void SynchronizeCalendarItems()
        {
           /* DataServiceCollection<i_CalendarItem> SubCalendarItemsC = new DataServiceCollection<i_CalendarItem>();
            SubCalendarItemsC.LoadCompleted += new EventHandler<LoadCompletedEventArgs>(SynchronizeCalendarItems_LoadCompleted);
            SubCalendarItemsC.LoadAsync(svc.CalendarItems);*/
        }//public void SynchronizeCalendarItems()

        private void SynchronizeCalendarItems_LoadCompleted(object sender, LoadCompletedEventArgs e)
        {
            /*
            DataServiceCollection<i_CalendarItem> CalendarItemsFromOdata = (DataServiceCollection<i_CalendarItem>)sender;
            if (e.Error == null)
            {
                if (CalendarItemsFromOdata.Continuation != null)
                    CalendarItemsFromOdata.LoadNextPartialSetAsync();
                else
                {
                    ObservableCollection<i_CalendarItem> TempCalendarItemsFromOdata = new ObservableCollection<i_CalendarItem>();
                    foreach (var CurrentCalendarItemFromOData in CalendarItemsFromOdata)
                        TempCalendarItemsFromOdata.Add(CurrentCalendarItemFromOData);
                    foreach (var CurrentCalendarItemFromOData in TempCalendarItemsFromOdata)
                    {
                        bool ExistInLocal = false;
                        foreach (var CurrentCalendarItemFromLocal in Data.CalendarItemsC)
                            if (CurrentCalendarItemFromLocal.CalendarItem_ID == CurrentCalendarItemFromOData.CalendarItem_ID)
                            {

                                //if (CurrentCalendarItemFromLocal.CalendarItem_ID == 23451)
                                //    ExistInLocal = false;
                                ExistInLocal = true;
                                if (CurrentCalendarItemFromLocal.Update_Date.HasValue && CurrentCalendarItemFromOData.Update_Date.HasValue)
                                    if (CurrentCalendarItemFromOData.Update_Date.Value > CurrentCalendarItemFromLocal.Update_Date.Value)
                                    {
                                        Data.CalendarItemsC.Remove(CurrentCalendarItemFromLocal); //update CalendarItem
                                        Data.CalendarItemsC.Add(CurrentCalendarItemFromOData);
                                    }
                                break;
                            }

                        if (!ExistInLocal)
                            Data.CalendarItemsC.Add(CurrentCalendarItemFromOData);//add new CalendarItem from Server
                    }//foreach (var CurrentCalendarItemFromOData in CalendarItemsFromOdata)

                    foreach (var CurrentCalendarItemFromLocal in Data.CalendarItemsC)
                    {
                        bool ExistOnServer = false;
                        foreach (var CurrentCalendarItemFromOData in TempCalendarItemsFromOdata)
                            if (CurrentCalendarItemFromLocal.CalendarItem_ID == CurrentCalendarItemFromOData.CalendarItem_ID)
                            {
                                ExistOnServer = true;
                                if (CurrentCalendarItemFromLocal.Update_Date.HasValue && CurrentCalendarItemFromOData.Update_Date.HasValue)
                                    if (CurrentCalendarItemFromLocal.Update_Date.Value > CurrentCalendarItemFromOData.Update_Date.Value)
                                    {
                                        CalendarItemsFromOdata.Remove(CurrentCalendarItemFromOData); //update CalendarItem
                                        CalendarItemsFromOdata.Add(CurrentCalendarItemFromLocal);
                                    }
                                break;
                            }
                        if (!ExistOnServer)
                            CalendarItemsFromOdata.Add(CurrentCalendarItemFromLocal);//add new CalendarItem from local
                    }//foreach (var CurrentCalendarItemFromLocal in Data.CalendarItemsC)

                    svc.BeginSaveChanges(SynchronizeCalendarItemsBeginSaveChangesCallback, svc);


                }//else if (CalendarItemsFromOdata.Continuation != null)
            }//if (e.Error == null)
            else
            {
                // Display the error returned by the data service.            
                //cw.Content = string.Format("An error has occured: {0}", e.Error.Message);
            }
            */
        }//private void SynchronizeCalendarItems_LoadCompleted(object sender, LoadCompletedEventArgs e)
        
        private void SynchronizeCalendarItemsBeginSaveChangesCallback(IAsyncResult result)
        {
            if (result.AsyncState is i7e)
                ((i7e)result.AsyncState).EndSaveChanges(result);
        }

        public void Add_and_Updatevw_Appointment_Summary_on_Client(i_vw_Appointment_Summary Currentvw_Appointment_Summary)
        {
            if (Currentvw_Appointment_Summary != null)
            siaqodb.StoreObject(Currentvw_Appointment_Summary);
        }

        public void Add_and_UpdateCalendarItem_on_Client(i_CalendarItem CurrentCalendarItem)
        {
            siaqodb.StoreObject(CurrentCalendarItem);
        }
        
        public void Add_and_UpdateCalendarItem_Field_on_Client()
        {
            if (TempAdd_and_UpdateCalendarItem_Field.Count <= 0)
                return;
            foreach (var CurCalendarItem_Field in TempAdd_and_UpdateCalendarItem_Field)
                siaqodb.StoreObject(CurCalendarItem_Field);         
        }

        public void SiaqodbFlush()
        {
            siaqodb.Flush();
        }

        public i_CalendarItem TempCalendarItemToUpdate = null;
        public void UpdateCalendarItem_on_Server()
        {
            if (TempCalendarItemToUpdate == null)
                return;
            var query = svc.CalendarItems.Where(a => a.CalendarItem_ID == TempCalendarItemToUpdate.CalendarItem_ID) as DataServiceQuery;
            query.BeginExecute(CalendarItemsAgentQueryCallBack, query);
        }//public void UpdateCalendarItem_on_Server()

        private void CalendarItemsAgentQueryCallBack(IAsyncResult result)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                var queryResult = result.AsyncState as DataServiceQuery<CalendarItem>;
                if (queryResult != null)
                {
                    var CalendarItemsFromODataT = queryResult.EndExecute(result);
                    DataServiceCollection<CalendarItem> CalendarItemsFromOData = new DataServiceCollection<CalendarItem>(svc);
                    foreach (var CurCalendarItem in CalendarItemsFromODataT)
                        CalendarItemsFromOData.Add(CurCalendarItem);
                    foreach (var CurCalendarItemFromOData in CalendarItemsFromOData)
                        if (CurCalendarItemFromOData.CalendarItem_ID == TempCalendarItemToUpdate.CalendarItem_ID)
                        {
                            //CurCalendarItemFromOData.CalendarItem_ID = Utils.ReverseIsNull(TempCalendarItemToUpdate.CalendarItem_ID).Value;
                            CurCalendarItemFromOData.CalendarItem_Calendar_ID = Utils.ReverseIsNull(TempCalendarItemToUpdate.CalendarItem_Calendar_ID);
                            CurCalendarItemFromOData.Verb_ID = Utils.ReverseIsNull(TempCalendarItemToUpdate.Verb_ID);
                            CurCalendarItemFromOData.Entry_ID = Utils.ReverseIsNull(TempCalendarItemToUpdate.Entry_ID);
                            CurCalendarItemFromOData.Entry_Name = Utils.ReverseIsNull(TempCalendarItemToUpdate.Entry_Name);
                            CurCalendarItemFromOData.Status_ID = Utils.ReverseIsNull(TempCalendarItemToUpdate.Status_ID);
                            CurCalendarItemFromOData.StatusNote = Utils.ReverseIsNull(TempCalendarItemToUpdate.StatusNote);
                            CurCalendarItemFromOData.isNoDate = Utils.ReverseIsNull(TempCalendarItemToUpdate.isNoDate);
                            CurCalendarItemFromOData.isAllDay = Utils.ReverseIsNull(TempCalendarItemToUpdate.isAllDay);
                            CurCalendarItemFromOData.isNote = Utils.ReverseIsNull(TempCalendarItemToUpdate.isNote);
                            CurCalendarItemFromOData.isRollover = Utils.ReverseIsNull(TempCalendarItemToUpdate.isRollover);
                            CurCalendarItemFromOData.isSpan = Utils.ReverseIsNull(TempCalendarItemToUpdate.isSpan);
                            CurCalendarItemFromOData.isEmailConfirmRequired = Utils.ReverseIsNull(TempCalendarItemToUpdate.isEmailConfirmRequired);
                            CurCalendarItemFromOData.Start_Date = Utils.ReverseIsNull(TempCalendarItemToUpdate.Start_Date);
                            CurCalendarItemFromOData.End_Date = Utils.ReverseIsNull(TempCalendarItemToUpdate.End_Date);
                            CurCalendarItemFromOData.Create_Date = Utils.ReverseIsNull(TempCalendarItemToUpdate.Create_Date);
                            CurCalendarItemFromOData.Update_Date = Utils.ReverseIsNull(TempCalendarItemToUpdate.Update_Date);
                            CurCalendarItemFromOData.Created_User_ID = Utils.ReverseIsNull(TempCalendarItemToUpdate.Created_User_ID);
                            CurCalendarItemFromOData.Updated_User_ID = Utils.ReverseIsNull(TempCalendarItemToUpdate.Updated_User_ID);
                            //CurCalendarItemFromOData.GUID = Utils.ReverseIsNull(TempCalendarItemToUpdate.GUID);
                            CurCalendarItemFromOData.Salutation = Utils.ReverseIsNull(TempCalendarItemToUpdate.Salutation);
                            CurCalendarItemFromOData.FirstName = Utils.ReverseIsNull(TempCalendarItemToUpdate.FirstName);
                            CurCalendarItemFromOData.MiddleName = Utils.ReverseIsNull(TempCalendarItemToUpdate.MiddleName);
                            CurCalendarItemFromOData.LastName = Utils.ReverseIsNull(TempCalendarItemToUpdate.LastName);
                            svc.UpdateObject(CurCalendarItemFromOData);
                        }

                    
                    svc.BeginSaveChanges(CalendarItemBeginSaveChangesCallback, svc);
                }//if (queryResult != null)
            });
        }//private void CalendarItemsAgentQueryCallBack(IAsyncResult result)

        private void CalendarItemBeginSaveChangesCallback(IAsyncResult result)
        {
            if (result.AsyncState is i7e)
            {
                try
                {
                    ((i7e)result.AsyncState).EndSaveChanges(result);
                    
                }
                catch (Exception exception)
                {
                    string ErrorS = exception.Message;
                }

                if (SaveOneCalendarIremCallbak != null)
                    SaveOneCalendarIremCallbak(null, new EventArgs());
            }
            TempCalendarItemToUpdate = null; 
        }

        public ObservableCollection<i_CalendarItem_Field> TempAdd_and_UpdateCalendarItem_Field = new ObservableCollection<i_CalendarItem_Field>();
        public void Add_and_UpdateCalendarItem_Field_on_Server()
        {
            int CurCalendarItem_ID = -1;
            if (TempAdd_and_UpdateCalendarItem_Field.Count > 0)
                CurCalendarItem_ID = TempAdd_and_UpdateCalendarItem_Field[0].CalendarItem_ID;
            else
                return;
            var query = svc.CalendarItem_Field.Where(a => a.CalendarItem_ID == CurCalendarItem_ID) as DataServiceQuery;
            query.BeginExecute(CalendarItem_FieldAgentQueryCallBack, query);
        }//public void Add_and_UpdateCalendarItem_Field(ObservableCollection<i_CalendarItem_Field> Add_and_UpdateCalendarItem_Field)

        private void CalendarItem_FieldAgentQueryCallBack(IAsyncResult result)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {    
                var queryResult = result.AsyncState as DataServiceQuery<CalendarItem_Field>;
                if (queryResult != null)
                {
                    var CalendarItem_FieldsFromODataT = queryResult.EndExecute(result);
                    DataServiceCollection<CalendarItem_Field> CalendarItem_FieldsFromOData = new DataServiceCollection<CalendarItem_Field>(svc);
                    foreach (var CurCalendarItem_Field in CalendarItem_FieldsFromODataT)
                        CalendarItem_FieldsFromOData.Add(CurCalendarItem_Field);
                    foreach (var CurCalendarItem_Field in TempAdd_and_UpdateCalendarItem_Field)
                    {
                        bool ExistOnServer = false;
                        foreach (var CurCalendarItem_FieldFromOData in CalendarItem_FieldsFromOData)
                            if (CurCalendarItem_FieldFromOData.CalendarItem_ID == CurCalendarItem_Field.CalendarItem_ID && 
                                CurCalendarItem_FieldFromOData.Field_ID == CurCalendarItem_Field.Field_ID )
                            {
                                CurCalendarItem_FieldFromOData.Value = CurCalendarItem_Field.Value;
                                CurCalendarItem_FieldFromOData.Sort =  Utils.ReverseIsNull( CurCalendarItem_Field.Sort);
                                CurCalendarItem_FieldFromOData.Field_Details_ID = Utils.ReverseIsNull(CurCalendarItem_Field.Field_Details_ID);                                
                                svc.UpdateObject(CurCalendarItem_FieldFromOData);
                                ExistOnServer = true;
                            }
                        if(!ExistOnServer)
                            svc.AddToCalendarItem_Field(i_CalendarItem_Field.ReverseConvert(CurCalendarItem_Field));
                    }//foreach (var CurCalendarItem_Field in TempAdd_and_UpdateCalendarItem_Field)
                    svc.BeginSaveChanges(CalendarItem_FieldBeginSaveChangesCallback, svc);
                }//if (queryResult != null)
            });
        }//private void CalendarItem_FieldAgentQueryCallBack(IAsyncResult result)


        private void CalendarItem_FieldBeginSaveChangesCallback(IAsyncResult result)
        {
            if (result.AsyncState is i7e)
            {
                
                try
                {
                    ((i7e)result.AsyncState).EndSaveChanges(result);
                }
                catch (Exception exception )
                {
                    string ErrorS = exception.Message;
                }
            }
            TempAdd_and_UpdateCalendarItem_Field.Clear();
        }

        public ObservableCollection<i_vw_Appointment_Summary> Getvw_Appointment_SummaryFromIsolatedStorage()
        {
            var vw_Appointment_Summary_from_Linq = from CalendarItemsO in Data.CalendarItemsC
                                                   join VerbO in Data.VerbC on CalendarItemsO.Verb_ID equals VerbO.Verb_ID
                                                   join EntryO in Data.EntryC on CalendarItemsO.Entry_ID equals EntryO.Entry_ID
                                                   join StatusO in Data.StatusC on CalendarItemsO.Status_ID equals StatusO.Status_ID
                                                   where (StatusO.Status_ID != 119 && StatusO.Status_ID != 123)
                                                   select new
                                                   {
                                                       CalendarItemsO.CalendarItem_ID,
                                                       CalendarItemsO.Salutation,
                                                       CalendarItemsO.FirstName,
                                                       CalendarItemsO.MiddleName,
                                                       CalendarItemsO.LastName,
                                                       VerbO.Verb_Name,
                                                       EntryO.Entry_Name,
                                                       CalendarItemsO.Start_Date,
                                                       CalendarItemsO.End_Date,
                                                       StatusO.Status_ID
                                                   };

            ObservableCollection<i_vw_Appointment_Summary> vw_Appointment_SummaryC = new ObservableCollection<i_vw_Appointment_Summary>();
            foreach (var Current_vw_Appointment_Summary_from_Linq in vw_Appointment_Summary_from_Linq)
                vw_Appointment_SummaryC.Add(new i_vw_Appointment_Summary()
                {
                    CalendarItem_ID = Current_vw_Appointment_Summary_from_Linq.CalendarItem_ID,
                    Salutation = Current_vw_Appointment_Summary_from_Linq.Salutation,
                    FirstName = Current_vw_Appointment_Summary_from_Linq.FirstName,
                    MiddleName = Current_vw_Appointment_Summary_from_Linq.MiddleName,
                    LastName = Current_vw_Appointment_Summary_from_Linq.LastName,
                    Entry_Name = Current_vw_Appointment_Summary_from_Linq.Entry_Name,
                    Verb = Current_vw_Appointment_Summary_from_Linq.Verb_Name,
                    Start_Date = Current_vw_Appointment_Summary_from_Linq.Start_Date,
                    End_Date = Current_vw_Appointment_Summary_from_Linq.End_Date,
                    Status_ID = Current_vw_Appointment_Summary_from_Linq.Status_ID
                });
            return vw_Appointment_SummaryC;
        }//public ObservableCollection<i_vw_Appointment_Summary> Getvw_Appointment_SummaryFromIsolatedStorage()

        public i_vw_Appointment_Summary GetOnevw_Appointment_SummaryFromIsolatedStorage(int CalendarItem_ID_Param = -1)
        {
            var vw_Appointment_Summary_from_Linq = from CalendarItemsO in Data.CalendarItemsC
                                                   join VerbO in Data.VerbC on CalendarItemsO.Verb_ID equals VerbO.Verb_ID
                                                   join EntryO in Data.EntryC on CalendarItemsO.Entry_ID equals EntryO.Entry_ID
                                                   join StatusO in Data.StatusC on CalendarItemsO.Status_ID equals StatusO.Status_ID
                                                   where (StatusO.Status_ID != 119 && StatusO.Status_ID != 123 && CalendarItemsO.CalendarItem_ID == CalendarItem_ID_Param)
                                                   select new
                                                   {
                                                       CalendarItemsO.CalendarItem_ID,
                                                       CalendarItemsO.Salutation,
                                                       CalendarItemsO.FirstName,
                                                       CalendarItemsO.MiddleName,
                                                       CalendarItemsO.LastName,
                                                       VerbO.Verb_Name,
                                                       EntryO.Entry_Name,
                                                       CalendarItemsO.Start_Date,
                                                       CalendarItemsO.End_Date,
                                                       StatusO.Status_ID
                                                   };

            if (vw_Appointment_Summary_from_Linq.Count() > 0)
            {
                var Current_vw_Appointment_Summary_from_Linq = vw_Appointment_Summary_from_Linq.First();
                i_vw_Appointment_Summary vw_Appointment_Summary = new i_vw_Appointment_Summary()
                    {
                        CalendarItem_ID = Current_vw_Appointment_Summary_from_Linq.CalendarItem_ID,
                        Salutation = Current_vw_Appointment_Summary_from_Linq.Salutation,
                        FirstName = Current_vw_Appointment_Summary_from_Linq.FirstName,
                        MiddleName = Current_vw_Appointment_Summary_from_Linq.MiddleName,
                        LastName = Current_vw_Appointment_Summary_from_Linq.LastName,
                        Entry_Name = Current_vw_Appointment_Summary_from_Linq.Entry_Name,
                        Verb = Current_vw_Appointment_Summary_from_Linq.Verb_Name,
                        Start_Date = Current_vw_Appointment_Summary_from_Linq.Start_Date,
                        End_Date = Current_vw_Appointment_Summary_from_Linq.End_Date,
                        Status_ID = Current_vw_Appointment_Summary_from_Linq.Status_ID
                    };
                return vw_Appointment_Summary;
            }
            else
                return null;
        }//public i_vw_Appointment_Summary GetOnevw_Appointment_SummaryFromIsolatedStorage(int CalendarItem_ID_Param = -1)

        public ObservableCollection<vw_Appointment_Detail> Getvw_Appointment_DetailFromIsolatedStorage(int CalendarItem_ID_Param = -1)
        {
            var vw_Appointment_Detail_from_Linq = CalendarItem_ID_Param != -1 ? 
                                                    (from CalendarItemsO in Data.CalendarItemsC
                                                    join EntryO in Data.EntryC on CalendarItemsO.Entry_ID equals EntryO.Entry_ID
                                                    join Entry_FieldO in Data.Entry_FieldC on CalendarItemsO.Entry_ID equals Entry_FieldO.Entry_ID
                                                    join FieldO in Data.FieldC on Entry_FieldO.Field_ID equals FieldO.Field_ID
                                                    join CalendarItem_FieldO in Data.CalendarItem_FieldC on new { CalendarItemsO.CalendarItem_ID, Entry_FieldO.Field_ID } equals new { CalendarItem_FieldO.CalendarItem_ID, CalendarItem_FieldO.Field_ID }
                                                                           where (CalendarItemsO.CalendarItem_ID == CalendarItem_ID_Param)
                                                    select new
                                                        {
                                                            CalendarItemsO.CalendarItem_ID,
                                                            CalendarItemsO.Salutation,
                                                            CalendarItemsO.FirstName,
                                                            CalendarItemsO.MiddleName,
                                                            CalendarItemsO.LastName,
                                                            CalendarItemsO.CalendarItem_Calendar_ID,
                                                            EntryO.Entry_ID,
                                                            FieldO.Field_Name,
                                                            CalendarItem_FieldO.Value,
                                                            CalendarItemsO.Entry_Name,
                                                            CalendarItemsO.StatusNote,
                                                            CalendarItemsO.Start_Date,
                                                            CalendarItemsO.End_Date
                                                        }) 
                                                        :
                                                    (from CalendarItemsO in Data.CalendarItemsC
                                                     join EntryO in Data.EntryC on CalendarItemsO.Entry_ID equals EntryO.Entry_ID
                                                     join Entry_FieldO in Data.Entry_FieldC on CalendarItemsO.Entry_ID equals Entry_FieldO.Entry_ID
                                                    join FieldO in Data.FieldC on Entry_FieldO.Field_ID equals FieldO.Field_ID
                                                    join CalendarItem_FieldO in Data.CalendarItem_FieldC on new { CalendarItemsO.CalendarItem_ID, Entry_FieldO.Field_ID } equals new { CalendarItem_FieldO.CalendarItem_ID, CalendarItem_FieldO.Field_ID }                                                   
                                                    select new
                                                        {
                                                            CalendarItemsO.CalendarItem_ID,
                                                            CalendarItemsO.Salutation,
                                                            CalendarItemsO.FirstName,
                                                            CalendarItemsO.MiddleName,
                                                            CalendarItemsO.LastName,
                                                            CalendarItemsO.CalendarItem_Calendar_ID,
                                                            EntryO.Entry_ID,
                                                            FieldO.Field_Name,
                                                            CalendarItem_FieldO.Value,
                                                            CalendarItemsO.Entry_Name,
                                                            CalendarItemsO.StatusNote,
                                                            CalendarItemsO.Start_Date,
                                                            CalendarItemsO.End_Date
                                                        }) 
                                                            ;

            ObservableCollection<vw_Appointment_Detail> vw_Appointment_DetailC = new ObservableCollection<i7SR.vw_Appointment_Detail>();
            foreach (var Current_vw_Appointment_Detail_from_Linq in vw_Appointment_Detail_from_Linq)
                vw_Appointment_DetailC.Add(new vw_Appointment_Detail()
                {
                    CalendarItem_ID = Current_vw_Appointment_Detail_from_Linq.CalendarItem_ID,
                    Salutation = Current_vw_Appointment_Detail_from_Linq.Salutation,
                    FirstName = Current_vw_Appointment_Detail_from_Linq.FirstName,
                    MiddleName = Current_vw_Appointment_Detail_from_Linq.MiddleName,
                    LastName = Current_vw_Appointment_Detail_from_Linq.LastName,
                    CalendarItem_Calendar_ID = Current_vw_Appointment_Detail_from_Linq.CalendarItem_Calendar_ID,
                    Entry_ID = Current_vw_Appointment_Detail_from_Linq.Entry_ID,
                    Field = Current_vw_Appointment_Detail_from_Linq.Field_Name,
                    Value = Current_vw_Appointment_Detail_from_Linq.Value,
                    Entry = Current_vw_Appointment_Detail_from_Linq.Entry_Name,
                    StatusNote = Current_vw_Appointment_Detail_from_Linq.StatusNote,
                    Start_Date = Current_vw_Appointment_Detail_from_Linq.Start_Date,
                    End_Date = Current_vw_Appointment_Detail_from_Linq.End_Date
                });
            return vw_Appointment_DetailC;
        }//public ObservableCollection<vw_Appointment_Detail> Getvw_Appointment_DetailFromIsolatedStorage(int CalendarItem_ID_Param = -1)


        public void Getvw_Appointment_DetailFromODataServer(int CalendarItem_ID_Param, int Entry_ID_Param = -1, i_CalendarItem NewCalendarItem = null)
        {
            string NewCalendarItemInBase64 = string.Empty;
            if (NewCalendarItem != null)
            {
                NewCalendarItemInBase64 = Convert.ToBase64String(SaveLoad.SaveToBinary(NewCalendarItem));
                NewCalendarItemInBase64 = System.Windows.Browser.HttpUtility.UrlEncode(NewCalendarItemInBase64);
            }
            
            
            WebClient vw_Appointment_Details_webC = new WebClient();
            
            string ParamsinS = "i_Getvw_Appointment_Detail_in_Binary_via_CustomFunction?CalendarItem_ID_Param=" +
                                                    CalendarItem_ID_Param.ToString() + "&Entry_ID_Param=" + Entry_ID_Param.ToString() +
                                                    "&NewCalendarItemInBase64='" + NewCalendarItemInBase64 + "'";
            string URLS = ODataServiceURL + ParamsinS;
            vw_Appointment_Details_webC.DownloadStringCompleted += new DownloadStringCompletedEventHandler(vw_Appointment_Details_DownloadStringCompleted);                                        
            vw_Appointment_Details_webC.DownloadStringAsync(new Uri(URLS));
            
            /*vw_Appointment_Details_webC.Headers["Content-Type"] = "application/x-www-form-urlencoded";
            vw_Appointment_Details_webC.UploadStringCompleted += new UploadStringCompletedEventHandler(vw_Appointment_Details_UploadStringCompleted);
            vw_Appointment_Details_webC.UploadStringAsync(new Uri(ODataServiceURL + "comment"), "Post",
                                                            "CalendarItem_ID_Param=" +
                                                                CalendarItem_ID_Param.ToString() + "&Entry_ID_Param=" + Entry_ID_Param.ToString() +
                                                                "&NewCalendarItemInBase64='" + NewCalendarItemInBase64 + "'");*/
        }//public ObservableCollection<vw_Appointment_Detail> Getvw_Appointment_DetailFromODataServer(int vw_Appointment_Detail_ID_Param)
 
        void vw_Appointment_Details_DownloadStringCompleted(object Sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                Thread ParseThread = new Thread(vw_Appointment_Details_ParseThread);
                ParseThread.Start(e.Result);                
            }//if (e.Error == null)
        }//void vw_Appointment_Details_DownloadStringCompleted(object Sender, DownloadStringCompletedEventArgs e)

        void vw_Appointment_Details_UploadStringCompleted(object Sender, UploadStringCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                Thread ParseThread = new Thread(vw_Appointment_Details_ParseThread);
                ParseThread.Start(e.Result);                
            }//if (e.Error == null)
        }//void vw_Appointment_Details_DownloadStringCompleted(object Sender, DownloadStringCompletedEventArgs e)

        private void vw_Appointment_Details_ParseThread(object DoParseThreadParam)
        {
            
            ObservableCollection<i_vw_Appointment_Detail> vw_Appointment_DetailList = (ObservableCollection<i_vw_Appointment_Detail>)SaveLoad.LoadFromBinary(FromXMLCustomOData_toBinary(DoParseThreadParam as string));
            if (GetAppointment_DetailFromODataServerCallbak != null)
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {    
                    GetAppointment_DetailFromODataServerCallbak(vw_Appointment_DetailList, new EventArgs());
                });
        }//private void vw_Appointment_Details_ParseThread(object DoParseThreadParam)
               
        
        public void SaveOneCalendarItemToODataServer(CalendarItem NewCI)
        {        
            //InitSvc();
            svc.AddToCalendarItems(NewCI);
            svc.BeginSaveChanges(BeginSaveChangesCallback, svc);
        }

        private void BeginSaveChangesCallback(IAsyncResult result)
        {   
            if (result.AsyncState is i7e)
            {
                foreach (var CurEntity in (result.AsyncState as i7e).Entities)
                    if (CurEntity.Entity is CalendarItem &&
                        CurEntity.State == EntityStates.Added &&
                        !string.IsNullOrEmpty(CurEntity.Identity))
                    {
                        string NewCalendarItemIDFromServerStr = CurEntity.Identity.Substring(CurEntity.Identity.IndexOf("(") + 1);
                        int NewCalendarItemIDFromServerInt = Convert.ToInt32( NewCalendarItemIDFromServerStr.Substring(0, NewCalendarItemIDFromServerStr.Length - 1));
                        int OldCalendarItem_ID = (CurEntity.Entity as CalendarItem).CalendarItem_ID;                        
                        foreach (var CurrentCalendarItem in Data.CalendarItemsC)
                            if (CurrentCalendarItem.CalendarItem_ID == OldCalendarItem_ID)
                            {
                                CurrentCalendarItem.CalendarItem_ID = NewCalendarItemIDFromServerInt;
                                break;
                            }
                        //(CurEntity.Entity as CalendarItem).CalendarItem_ID = NewCalendarItemIDFromServerInt;                        
                        try
                        {
                            ((i7e)result.AsyncState).EndSaveChanges(result);
                            
                        }
                        catch (Exception exception)
                        {
                            string ErrorS = exception.Message;
                        }

                        if (SaveOneCalendarIremCallbak != null)
                            SaveOneCalendarIremCallbak(NewCalendarItemIDFromServerInt, new EventArgs());
                        break;
                    }
                 
            }
        }

        public void DeleteAllFilesInIsolatedStorage()
        {
            if (IsolatedStorageFile.GetUserStoreForApplication().FileExists(SaveLoad.IvvySilverlightFileNameinIsolatedStorageBinary))
                IsolatedStorageFile.GetUserStoreForApplication().DeleteFile(SaveLoad.IvvySilverlightFileNameinIsolatedStorageBinary);
            if (IsolatedStorageFile.GetUserStoreForApplication().FileExists(SaveLoad.IvvySilverlightFileNameinIsolatedStorage))
                IsolatedStorageFile.GetUserStoreForApplication().DeleteFile(SaveLoad.IvvySilverlightFileNameinIsolatedStorage);
        }//public void DeleteAllFilesInIsolatedStorage()

        public bool LoadCollectionsCompleted_IsNull()
        {
            return LoadCollectionsCompleted == null;
        }

        public bool LoadCollectionsProgressCallbak_IsNull()
        {
            return LoadCollectionsProgressCallbak == null;
        }

    }//public class DataManipulations

    public class ClientData
    {
        public ObservableCollection<i_CalendarItem> CalendarItemsC = null;
        public ObservableCollection<i_Calendar> CalendarsC = null;
        public ObservableCollection<i_vw_Appointment_Summary> vw_Appointment_SummaryC = null;
        public ObservableCollection<i_CalendarItem_Field> CalendarItem_FieldC = null;
        public ObservableCollection<i_vw_CalendarItem_Note> vw_CalendarItem_NoteC = null;
        public ObservableCollection<i_Entry> EntryC = null;
        public ObservableCollection<i_Entry_Field> Entry_FieldC = null;
        public ObservableCollection<i_Field> FieldC = null;
        public ObservableCollection<i_Field_Details> Field_DetailsC = null;
        public ObservableCollection<i_Field_Type> Field_TypeC = null;        
        public ObservableCollection<i_Verb> VerbC = null;
        public ObservableCollection<i_Status> StatusC = null;
        public ObservableCollection<i_CalendarItem_Related> CalendarItem_RelatedC = null;
        public ObservableCollection<i_CalendarItemRecurrence> CalendarItemRecurrenceC = null;
        
        public ClientData()
        {
            CalendarItemsC = new ObservableCollection<i_CalendarItem>();
            CalendarsC = new ObservableCollection<i_Calendar>();
            vw_Appointment_SummaryC = new ObservableCollection<i_vw_Appointment_Summary>();            
            CalendarItem_FieldC = new ObservableCollection<i_CalendarItem_Field>();
            vw_CalendarItem_NoteC = new ObservableCollection<i_vw_CalendarItem_Note>();
            EntryC = new ObservableCollection<i_Entry>();
            Entry_FieldC = new ObservableCollection<i_Entry_Field>();
            FieldC = new ObservableCollection<i_Field>();
            Field_DetailsC = new ObservableCollection<i_Field_Details>();
            Field_TypeC = new ObservableCollection<i_Field_Type>();            
            VerbC = new ObservableCollection<i_Verb>();
            StatusC = new ObservableCollection<i_Status>();
            CalendarItem_RelatedC = new ObservableCollection<i_CalendarItem_Related>();
            CalendarItemRecurrenceC = new ObservableCollection<i_CalendarItemRecurrence>();
        }//public ClientData()

        public void ClearAll()
        {
            CalendarItemsC.Clear();
            CalendarsC.Clear();
            vw_Appointment_SummaryC.Clear();            
            CalendarItem_FieldC.Clear();
            vw_CalendarItem_NoteC.Clear();
            EntryC.Clear();
            Entry_FieldC.Clear();
            FieldC.Clear();
            Field_DetailsC.Clear();
            Field_TypeC.Clear();            
            VerbC.Clear();
            StatusC.Clear();
            CalendarItem_RelatedC.Clear();
            CalendarItemRecurrenceC.Clear();
        }//public void ClearAll()

        public int GetTotalCount()
        {
            return CalendarItemsC.Count +
            CalendarsC.Count +            
            CalendarItem_FieldC.Count +
            vw_CalendarItem_NoteC.Count +
            EntryC.Count +
            Entry_FieldC.Count +
            FieldC.Count +
            Field_DetailsC.Count +
            Field_TypeC.Count +
            VerbC.Count +
            StatusC.Count +
            CalendarItem_RelatedC.Count +
            CalendarItemRecurrenceC.Count;
        }


    }//public class ClientData


}//namespace Ivvy_Silverlight.Ivvy
